package com.base.mine;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.utils.SystemUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.commonlib.widget.CommonDialog;
import com.base.commonlib.widget.CommonSingleDialog;
import com.base.mine.bean.TaskInfo;
import com.base.mine.config.RouteConfig;
import com.base.mine.databinding.ActivityVersionBinding;
import com.base.mine.presenter.VersionPresenter;
import com.base.mine.utils.DownloadRunnable;
import com.base.mine.view.VersionView;

import java.io.File;

/**
 * Created by weikailiang on 2019/2/25.
 */
@Route(path = RouteConfig.ACTIVITY_VERSION)
public class VersionActivity extends CBaseBarMvpActivity<VersionPresenter> implements VersionView {
    private ActivityVersionBinding mBinding;


    private DownloadRunnable runnable;//下载任务
    private TaskInfo info = null;//任务信息
    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};


    @Override
    protected void init() {
        super.init();
        setBarTitle("版本更新");
        setBackNavigation();
        mBinding = (ActivityVersionBinding) mRootBinding;
    }


    Dialog mDialog;
    ProgressBar bar;
    TextView text;
    ImageView mPause;
    boolean b;
    private void showDownDialog(){
        mDialog = new Dialog(this);
        View v = LayoutInflater.from(this).inflate(R.layout.item_dialog,null);
        bar = v.findViewById(R.id.progress_bar);
        mPause = v.findViewById(R.id.pause);
        text = v.findViewById(R.id.num);
        mDialog.setContentView(v);
        mDialog.setCancelable(false);
        mDialog.setTitle("您有新版本");
        mDialog.show();
        mPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!b){
                    mPause.setImageResource(R.mipmap.ic_start);
                    stop(null);
                }else {
                    mPause.setImageResource(R.mipmap.ic_pause);
                    startApk(null);
                }
                b = !b;
            }
        });
        startApk(null);
    }
    @Override
    protected void onDestroy() {
        //在Activity销毁时移除回调和msg，并置空，防止内存泄露
        if(handler != null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }

    @Override
    protected int getLayoutResource() {
        return  R.layout.activity_version;
    }


    /**
     * 开始下载按钮监听
     * @param view
     */
    public void startApk(View view) {
        //创建下载任务
        runnable = new DownloadRunnable(info);
        //开始下载任务
        new Thread(runnable).start();
        //开始Handler循环
        handler.sendEmptyMessageDelayed(1, 200);
    }

    /**
     * 停止下载按钮监听
     * @param view
     */
    public void stop(View view) {
        //调用DownloadRunnable中的stop方法，停止下载
        runnable.stop();
        runnable = null;//强迫症，不用的对象手动置空
    }


    //用于更新进度的Handler
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //使用Handler制造一个200毫秒为周期的循环
            handler.sendEmptyMessageDelayed(1, 200);

            if (info.getContentLen()==0){
                //为获取到文件长度
                if (info.isCommpany()){
                    bar.setProgress(100);
                    text.setText(100 + "%");
                    handler.removeCallbacksAndMessages(null);
                    if (mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    checkIsAndroidO();
                }else {
                    text.setText("正在下载中，请等待");
                }
            }else {
                //计算下载进度
                int l = (int) ((float) info.getCompletedLen() / (float) info.getContentLen() * 100);
                //设置进度条进度
                bar.setProgress(l);
                text.setText(l + "%");
                if (l >= 100) {//当进度>=100时，取消Handler循环
                    handler.removeCallbacksAndMessages(null);
                    if (mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    checkIsAndroidO();

                }
            }
            return true;
        }
    });



    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {
        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于下载文件需要获取存储空间，为你存储文件；\n否则，您将无法正常下载")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }
    // 开始提交请求权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void startRequestPermission() {
        requestPermissions(permissions, 321);
    }
    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else {
                        Toast.makeText(this,"抱歉，您拒绝了权限，无法下载", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                } else {
                    mPresenter.CheckVersion();
                }
            }
        }
    }
    // 提示用户去应用设置界面手动开启权限
    AlertDialog dialog;
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许本应用使用存储权限来下载文件")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }
    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = checkSelfPermission(permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    mPresenter.CheckVersion();
                }
            }
        }else if (requestCode == 10012) {
            checkIsAndroidO();
        }
    }




    private void checkIsAndroidO() {
//        if (Build.VERSION.SDK_INT >= 26) {
//            boolean b = getPackageManager().canRequestPackageInstalls();
//            if (b) {
//                installApk(mContext, info.getPath() + info.getName());
//            } else {
//                //设置安装未知应用来源的权限
//                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//                startActivityForResult(intent, 10012);
//            }
//        } else {
            installApk(mContext, info.getPath() + info.getName());
//            openFile(new File(info.getPath() + info.getName()), mContext);
//        }
    }

    /**
     * 安装APK
     *
     * @param context
     * @param apkPath
     */
    public static void installApk(Context context, String apkPath) {
        if (context == null || TextUtils.isEmpty(apkPath)) {
            return;
        }
        File file = new File(apkPath);
        if (!file.exists()){
            ToastUtil.show("安装包路径不正确，请联系管理员");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(context, "com.yookey.study", file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    @Override
    public void hasNewVersion(TaskInfo info) {
        this.info = info;

        CommonSingleDialog dialog = new CommonSingleDialog(mContext,info.getRemark());
        dialog.setCancelable(false);
        dialog.setOnPosClick(new CommonSingleDialog.OnPosClick() {
            @Override
            public void onClick() {
                showDownDialog();
            }
        });
        dialog.show();
    }

    @Override
    protected void start() {
        mPresenter = new VersionPresenter(this,this);

        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = checkSelfPermission(permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                showDialogTipUserRequestPermission();
            }else {
                mPresenter.CheckVersion();
            }
        }else {
            mPresenter.CheckVersion();
        }
        mBinding.versionNumber.setText(SystemUtil.packageName(mContext));
        mBinding.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int i = checkSelfPermission(permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求
                        showDialogTipUserRequestPermission();
                    }else {
                        mPresenter.CheckVersion();
                    }
                }else {
                    mPresenter.CheckVersion();
                }
            }
        });
    }
}
